import java.util.*;
import java.io.*;
import java.util.Date;


public class Main {
   
    public static void main(String[] args) throws InterruptedException{
    	String mode = "minimal";
        int timeout = 30;
        int time = 1000;
        String[] hostport;
        String nodeAddress = new String();
        int nodePort = 0;
        String resultPath = "crawlresult.txt";
        long startTime = System.currentTimeMillis();
        Date startDate = new Date();
        Date endDate = new Date();
                
        // PARSE ARGUMENTS
        if (args.length < 3){
            System.out.println("Error: incorrect inputs\nUsage:\n\t" +
            		"java crawler <-full|-minimal> <timeout=XX> <host:port> <time>");
            return;
        }
        else{
        	for (int i=0; i<args.length; i++) {
        		if(args[i].compareTo("-minimal") == 0)
        			mode = "minimal";
        		if(args[i].compareTo("-full") == 0)
        			mode = "full";
        		if(args[i].contains(":")) {
        			hostport = args[i].split(":");
        			nodeAddress = hostport[0];
	            	nodePort = Integer.parseInt(hostport[1]);
        		}
        		if(args[i].startsWith("timeout"))
        			timeout = Integer.parseInt(args[i].split("=")[1]);
        		if(i == args.length-1)
        			time = Integer.parseInt(args[i]);
        			//time = Integer.parseInt(args[i].split("=")[1]);
        	}
        	System.out.println("mode=" + mode + " timeout=" + timeout + " host=" + nodeAddress + ":" + nodePort + " time=" + time);
        }
        
        // START THE CRAWL MASTER
        CrawlMaster mct = new CrawlMaster(nodeAddress, nodePort, timeout, resultPath);
        mct.start();
                
        // Kill the Master once 'time' seconds have passed
        while (mct.isAlive()) {
        	//mct.join();
        	if (((System.currentTimeMillis() - startTime) > time*1000)) {
        		System.out.println("Program timeout reached");
        		endDate = new Date();
        		mct.interrupt();
        		mct.join();
        	} else {
        		Thread.sleep(1000);
        	}
        }
        
        // Read the Text File
        ObjectReader crawlReader = new ObjectReader();
		List<CrawlResult> finalResult = crawlReader.readCrawlResult(resultPath);
		
		System.out.println("Aggregating Stats...");
		//Aggregated data and print out some statistics
		Aggregate agg = new Aggregate(mode, finalResult, time, startDate, endDate);
		//agg.printStatistics(); 
		System.out.println("Done!");
        System.exit(0);
            
    }   
}
